import pymongo
from datetime import datetime
from django.conf import settings

class MongoDBConnection:
    """MongoDB连接管理类"""
    
    def __init__(self):
        self.config = settings.MONGODB_CONFIG
        self.client = None
        self.db = None
    
    def connect(self):
        """连接MongoDB"""
        try:
            # 构建连接字符串
            connection_string = f"mongodb://{self.config['username']}:{self.config['password']}@{self.config['host']}:{self.config['port']}/{self.config['database']}?authSource={self.config['auth_source']}&authMechanism={self.config['auth_mechanism']}"
            
            # 创建客户端连接
            self.client = pymongo.MongoClient(connection_string)
            
            # 测试连接
            self.client.admin.command('ping')
            
            # 获取数据库
            self.db = self.client[self.config['database']]
            
            print("MongoDB连接成功")
            return True
            
        except Exception as e:
            print(f"MongoDB连接失败: {str(e)}")
            return False
    
    def close(self):
        """关闭MongoDB连接"""
        if self.client:
            self.client.close()
            print("MongoDB连接已关闭")
    
    def get_collection(self, collection_name):
        """获取集合"""
        if self.db is None:
            if not self.connect():
                return None
        return self.db[collection_name]

# 全局MongoDB连接实例
mongo_connection = MongoDBConnection()

class PendingComment:
    """待审核评论MongoDB操作类"""
    
    def __init__(self):
        self.collection = mongo_connection.get_collection('pending_comments')
    
    def create_comment(self, comment_data):
        """创建待审核评论"""
        try:
            # 添加创建时间
            comment_data['create_time'] = datetime.now()
            comment_data['audit_status'] = 0  # 0-待审核
            
            # 插入文档
            result = self.collection.insert_one(comment_data)
            
            if result.inserted_id:
                print(f"待审核评论创建成功: {result.inserted_id}")
                return str(result.inserted_id)
            else:
                print("待审核评论创建失败")
                return None
                
        except Exception as e:
            print(f"创建待审核评论失败: {str(e)}")
            return None
    
    def get_comment_by_id(self, comment_id):
        """根据ID获取评论"""
        try:
            from bson import ObjectId
            doc = self.collection.find_one({'_id': ObjectId(comment_id)})
            
            if doc:
                # 转换ObjectId为字符串
                doc['_id'] = str(doc['_id'])
                return doc
            else:
                return None
                
        except Exception as e:
            print(f"获取评论失败: {str(e)}")
            return None
    
    def update_audit_status(self, comment_id, audit_status, audit_result=None, sensitive_words=None):
        """更新审核状态"""
        try:
            from bson import ObjectId
            
            update_data = {
                'audit_status': audit_status,
                'audit_time': datetime.now()
            }
            
            if audit_result:
                update_data['audit_result'] = audit_result
            if sensitive_words:
                update_data['sensitive_words'] = sensitive_words
            
            result = self.collection.update_one(
                {'_id': ObjectId(comment_id)},
                {'$set': update_data}
            )
            
            if result.modified_count > 0:
                print(f"评论审核状态更新成功: {comment_id}")
                return True
            else:
                print(f"评论审核状态更新失败: {comment_id}")
                return False
                
        except Exception as e:
            print(f"更新审核状态失败: {str(e)}")
            return False
    
    def get_pending_comments(self, limit=100):
        """获取待审核评论列表"""
        try:
            cursor = self.collection.find(
                {'audit_status': 0}  # 只获取待审核的评论
            ).sort('create_time', -1).limit(limit)
            
            comments = []
            for doc in cursor:
                doc['_id'] = str(doc['_id'])
                comments.append(doc)
            
            return comments
            
        except Exception as e:
            print(f"获取待审核评论失败: {str(e)}")
            return []
    
    def delete_comment(self, comment_id):
        """删除评论"""
        try:
            from bson import ObjectId
            
            result = self.collection.delete_one({'_id': ObjectId(comment_id)})
            
            if result.deleted_count > 0:
                print(f"评论删除成功: {comment_id}")
                return True
            else:
                print(f"评论删除失败: {comment_id}")
                return False
                
        except Exception as e:
            print(f"删除评论失败: {str(e)}")
            return False
    
    def get_comments_by_order(self, order_id):
        """根据订单ID获取评论"""
        try:
            cursor = self.collection.find({'order_id': order_id}).sort('create_time', -1)
            
            comments = []
            for doc in cursor:
                doc['_id'] = str(doc['_id'])
                comments.append(doc)
            
            return comments
            
        except Exception as e:
            print(f"根据订单ID获取评论失败: {str(e)}")
            return []
    
    def get_comments_by_driver(self, driver_id):
        """根据司机ID获取评论"""
        try:
            cursor = self.collection.find({'driver_id': driver_id}).sort('create_time', -1)
            
            comments = []
            for doc in cursor:
                doc['_id'] = str(doc['_id'])
                comments.append(doc)
            
            return comments
            
        except Exception as e:
            print(f"根据司机ID获取评论失败: {str(e)}")
            return []
    
    def get_comments_with_images(self):
        """获取包含图片的评论（七牛云URL）"""
        try:
            cursor = self.collection.find(
                {'image_url': {'$exists': True, '$ne': None}}
            ).sort('create_time', -1)
            
            comments = []
            for doc in cursor:
                doc['_id'] = str(doc['_id'])
                comments.append(doc)
            
            return comments
            
        except Exception as e:
            print(f"获取包含图片的评论失败: {str(e)}")
            return []
    
    def update_comment(self, comment_id, update_data):
        """更新评论内容"""
        try:
            from bson import ObjectId
            
            # 添加更新时间
            update_data['update_time'] = datetime.now()
            
            result = self.collection.update_one(
                {'_id': ObjectId(comment_id)},
                {'$set': update_data}
            )
            
            if result.modified_count > 0:
                print(f"评论更新成功: {comment_id}")
                return True
            else:
                print(f"评论更新失败: {comment_id}")
                return False
                
        except Exception as e:
            print(f"更新评论失败: {str(e)}")
            return False
    
    def get_audit_statistics(self):
        """获取审核统计信息"""
        try:
            # 统计各状态的评论数量
            pipeline = [
                {
                    '$group': {
                        '_id': '$audit_status',
                        'count': {'$sum': 1}
                    }
                }
            ]
            
            result = list(self.collection.aggregate(pipeline))
            
            stats = {
                'pending': 0,    # 待审核
                'approved': 0,   # 已通过
                'rejected': 0,   # 已拒绝
                'total': 0       # 总数
            }
            
            for item in result:
                status = item['_id']
                count = item['count']
                
                if status == 0:
                    stats['pending'] = count
                elif status == 1:
                    stats['approved'] = count
                elif status == 2:
                    stats['rejected'] = count
                
                stats['total'] += count
            
            return stats
            
        except Exception as e:
            print(f"获取审核统计信息失败: {str(e)}")
            return {
                'pending': 0,
                'approved': 0,
                'rejected': 0,
                'total': 0
            } 